package fr.unice.polytech.chord.gui.components;

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

/**
 * JLimitedSizeTextField allow to limit the text field size to a specified
 * number of characters.
 * 
 * @author Anthony Parisy
 * @author Laurent Pellegrino
 * @author Marc Valdener
 * 
 * @version 06/11/2009
 */
@SuppressWarnings("serial")
public class JLimitedSizeTextField extends JTextField {
	private int maxLength;

	public JLimitedSizeTextField(int columns, int maxLength) {
		super(columns);
		this.maxLength = maxLength;
		if (maxLength <= 0) {
			maxLength = -1;
		}
	}

	protected Document createDefaultModel() {
		return new LimitedSizePlainDocument();
	}

	class LimitedSizePlainDocument extends PlainDocument {
		public void insertString(int offset, String str, AttributeSet attr)
				throws BadLocationException {
			if (str == null) {
				return;
			}
			if (maxLength == -1 || getLength() + str.length() <= maxLength) {
				super.insertString(offset, str, attr);
			}
		}
	}
}